/**
*
*  Original Crossbrowser Drag Handler
*  http://www.webtoolkit.info/
*
**/

function DragHandler(oElem, oHandler)
{

	var	_oElem = oElem, _oHandler = oHandler,
		_mouseX, mouseY;

	this.detach = detach;
	this.dispose = detach;

	attach(oElem, oHandler);


    // public method. Attach drag handler to an element.
	function attach(oElem, oHandler)
	{
		var elem = _oHandler;
		if (elem == null)
        		elem = oElem;

//		elem.onmousedown = _dragBegin;
		utils.attachEvent(elem, 'mousedown', _dragBegin);

        	// callbacks
		oElem.dragBegin = new Function();
		oElem.drag = new Function();
		oElem.dragEnd = new Function();
	}


	function detach()
	{
		var elem = _oHandler;
		if (elem == null)
        		elem = oElem;

		utils.detachEvent(elem, 'mousedown', _dragBegin)
	}

    // private method. Begin drag process.
    function _dragBegin(e) {
        var oElem = _oElem;

        if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
        if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        e = e ? e : window.event;
        _mouseX = e.clientX;
        _mouseY = e.clientY;

        oElem.dragBegin(oElem, x, y);

//        document.onmousemove = _drag;
//        document.onmouseup = _dragEnd;

	utils.attachEvent(document, 'mousemove', _drag);
	utils.attachEvent(document, 'mouseup', _dragEnd);

        return false;
    }


    // private method. Drag (move) element.
    function _drag(e) {
        var oElem = _oElem;

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        e = e ? e : window.event;
	var left = x + (e.clientX - _mouseX);
	var top = y + (e.clientY - _mouseY);

	if ((left < 0) || (e.clientX <= 0))
		left = 0;

	if ((top < 0) || (e.clientY <= 0))
		top = 0;

	oElem.style.left = left + 'px';
	oElem.style.top  = top  + 'px';

        _mouseX = e.clientX;
        _mouseY = e.clientY;

        oElem.drag(oElem, x, y);

        return false;
    }


    // private method. Stop drag process.
    function _dragEnd() {
        var oElem = _oElem;

        var x = parseInt(oElem.style.left);
        var y = parseInt(oElem.style.top);

        oElem.dragEnd(oElem, x, y);

//        document.onmousemove = null;
//        document.onmouseup = null;

	utils.detachEvent(document, 'mousemove', _drag);
	utils.detachEvent(document, 'mouseup', _dragEnd);
    }

}